package services

import (
	"encoding/json"
	"errors"
	"homepage-backend/internal/models"
	"os"
	"path/filepath"
	"sync"
	"time"
)

var (
	musicShares     = make(map[string]models.MusicShare)
	shareMutex      sync.RWMutex
	shareStorageDir = "data/music_shares"
	shareFilePath   = filepath.Join(shareStorageDir, "shares.json")
)

// InitMusicShareService 初始化音乐分享服务
func InitMusicShareService() error {
	// 创建存储目录（包括所有父目录）
	if err := os.MkdirAll(shareStorageDir, 0755); err != nil {
		return errors.New("创建音乐分享存储目录失败: " + err.Error())
	}

	// 尝试加载现有的分享数据
	if err := loadShares(); err != nil {
		if !os.IsNotExist(err) {
			return errors.New("加载音乐分享数据失败: " + err.Error())
		}
		// 如果文件不存在，创建空的分享数据文件
		musicShares = make(map[string]models.MusicShare)
		if err := saveShares(); err != nil {
			return errors.New("创建音乐分享数据文件失败: " + err.Error())
		}
	}

	LogInfo("音乐分享服务初始化成功，存储目录：%s", shareStorageDir)
	return nil
}

// SaveShare 保存分享记录
func SaveShare(share models.MusicShare) (string, error) {
	shareMutex.Lock()
	defer shareMutex.Unlock()

	// 使用 TrackID + ServerURL + Comment 的组合生成唯一标识符
	uniqueKey := share.TrackID + "-" + share.ServerURL + "-" + share.Comment
	generatedID := GenerateShortID(uniqueKey)
	share.ID = generatedID
	share.ShareTime = time.Now().Unix()

	musicShares[generatedID] = share
	if err := saveShares(); err != nil {
		return "", errors.New("保存音乐分享数据失败: " + err.Error())
	}
	return generatedID, nil
}

// GetShare 获取分享记录
func GetShare(id string) (models.MusicShare, bool) {
	shareMutex.RLock()
	defer shareMutex.RUnlock()

	share, exists := musicShares[id]
	if !exists {
		return models.MusicShare{}, false
	}

	return share, true
}

// GetAllShares 获取所有音乐分享（管理用）
func GetAllShares() []models.MusicShare {
	shareMutex.RLock()
	defer shareMutex.RUnlock()
	result := make([]models.MusicShare, 0, len(musicShares))
	for _, v := range musicShares {
		result = append(result, v)
	}
	return result
}

// DeleteShare 删除指定id的音乐分享
func DeleteShare(id string) error {
	shareMutex.Lock()
	defer shareMutex.Unlock()
	if _, ok := musicShares[id]; !ok {
		return errors.New("not found")
	}
	delete(musicShares, id)
	return saveShares()
}

// loadShares 从文件加载分享数据
func loadShares() error {
	data, err := os.ReadFile(shareFilePath)
	if err != nil {
		return err
	}

	shareMutex.Lock()
	defer shareMutex.Unlock()

	return json.Unmarshal(data, &musicShares)
}

// saveShares 保存分享数据到文件
func saveShares() error {
	// 使用美化的JSON格式
	data, err := json.MarshalIndent(musicShares, "", "  ")
	if err != nil {
		return err
	}
	return os.WriteFile(shareFilePath, data, 0644)
}
